package com.mall.common.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mall.common.bean.AdvertBean;
import com.mall.common.bean.Order;
import com.mall.common.bean.Order.Direction;
import com.mall.common.dao.AdvertDao;
import com.mall.common.domain.content.AdvertDomain;
import com.mall.common.hibernate.Finder;
import com.mall.common.hibernate.Updater;
import com.mall.common.service.AdvertService;
import com.mall.common.util.DateHelper;


/**
 * Service实现类 - 广告
 */
@Service
@Transactional
public class AdvertServiceImpl extends BaseServiceImpl<AdvertDomain, Long> implements AdvertService {
	
	@Resource
	public void setBaseDao(AdvertDao advertDao) { 
		super.setBaseDao(advertDao); 
	}

	@Override
	@Cacheable(value="adPosition", key="'advert'+#position+','+#num")
	public List<AdvertBean> getAdverts(String position, Integer num) {
		Finder finder = Finder.create("select new com.mall.common.bean.AdvertBean(bean) from AdvertDomain bean where bean.isOpen = true");
		finder.append(" and (bean.startTime is null or DATE_FORMAT(bean.startTime, '%Y-%m-%d') <= :today)");
		finder.append(" and (bean.endTime is null or DATE_FORMAT(bean.endTime, '%Y-%m-%d') >= :today)");
		finder.setOrder(Order.asc("priority"));
		if(StringUtils.isNotBlank(position)){
			finder.append(" and bean.advertPosition.position = :position");
			finder.setParam("position", position);
		}
		if(num != null){
			finder.setMaxResults(num);
		}
		finder.setOrder(new Order("bean.priority", Direction.asc));
		String today = DateHelper.date2String(new Date(), "yyyy-MM-dd");
		finder.setParam("today", today);
		return finder.findHQLList();
	}

	@Override
	@CacheEvict(value="adPosition",allEntries=true)
	@Transactional(propagation=Propagation.REQUIRED)
	public AdvertDomain updateByUpdater(Updater<AdvertDomain> updater) {
		return super.updateByUpdater(updater);
	}

	@Override
	@CacheEvict(value="adPosition",allEntries=true)
	@Transactional(propagation=Propagation.REQUIRED)
	public void persist(AdvertDomain entity) {
		super.persist(entity);
	}

}
